<template>
  <div class="chat-container">
    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContent">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.sender === 'user' ? 'user-message' : 'bot-message']"
      >
        <div v-if="message.sender === 'user'" class="avatar user-avatar">
          <a-icon type="user" />
        </div>
        <div v-else class="avatar bot-avatar">
          <a-icon type="robot" />
        </div>

        <div class="message-content">
          <div v-html="message.content"></div>
          <div class="timestamp">{{ message.timestamp }}</div>
        </div>
      </div>

      <div v-if="isLoading" class="message bot-message">
        <div class="avatar bot-avatar">
          <a-icon type="robot" />
        </div>
        <div class="loading-dots">
          <div class="dot"></div>
          <div class="dot"></div>
          <div class="dot"></div>
        </div>
      </div>
    </div>

    <!-- 固定输入区域 -->
    <div class="input-area">
      <a-input
        v-model="inputMessage"
        placeholder="输入您的问题..."
        @pressEnter="sendMessage"
        :disabled="isLoading"
      >
        <a-icon slot="prefix" type="message" />
      </a-input>
      <a-button
        type="primary"
        shape="circle"
        icon="arrow-up"
        class="send-button"
        @click="sendMessage"
        :loading="isLoading"
      />
    </div>
  </div>
</template>

<script>
import { chat, getChatHistory } from '@/api/ai/chat'

export default {
  name: 'FixedInputChat',
  props: {
    height: {
      type: String,
      default: '750px'
    }
  },
  data () {
    return {
      inputMessage: '',
      messages: [
        {
          sender: 'bot',
          content: '您好！我是Snail系统的AI助手，有什么可以帮您的吗？',
          timestamp: this.getCurrentTime()
        }
      ],
      isLoading: false
    }
  },
  methods: {
    async sendMessage () {
      if (!this.inputMessage.trim() || this.isLoading) return

      const userMessage = {
        sender: 'user',
        content: this.inputMessage,
        timestamp: this.getCurrentTime()
      }

      this.messages.push(userMessage)

      const userInput = this.inputMessage
      this.inputMessage = ''

      this.isLoading = true

      // 滚动到底部
      this.scrollToBottom()

      try {
        // 调用API
        const response = await chat({ query: userInput, filePath: '' })

        const botMessage = {
          sender: 'bot',
          content: response.content,
          timestamp: this.getCurrentTime()
        }

        this.messages.push(botMessage)
      } catch (error) {
        console.error('Error:', error)
        this.messages.push({
          sender: 'bot',
          content: '<p>抱歉，处理您的请求时出现了问题。请稍后再试。</p>',
          timestamp: this.getCurrentTime()
        })
      } finally {
        this.isLoading = false
        // 确保滚动到底部
        this.scrollToBottom()
      }
    },

    getCurrentTime () {
      const now = new Date()
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    },

    scrollToBottom () {
      this.$nextTick(() => {
        const container = this.$refs.chatContent
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    // 初始化对话记录
    async initDialogHis () {
      const res = await getChatHistory()
      if (res.data) {
        this.messages = []
      }
      // 倒序遍历数据
      for (let i = res.data.length - 1; i >= 0; i--) {
        const message = res.data[i]
        const humanMsg = message[0]
        const botMsg = message[1]
        this.messages.push({
          sender: 'user',
          content: humanMsg.content,
          timestamp: humanMsg.timestamp
        })
        this.messages.push({
          sender: 'bot',
          content: botMsg.content,
          timestamp: botMsg.timestamp
        })
      }
    }
  },
  watch: {
    // 当消息变化时滚动到底部
    messages () {
      this.scrollToBottom()
    }
  },
  mounted () {
    this.scrollToBottom()
  },
  created () {
    this.initDialogHis()
  }
}
</script>

<style lang="less" scoped>
@import "~ant-design-vue/dist/antd.less";

.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: v-bind('height');
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  border: 1px solid #f0f0f0;
  position: relative;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: #fafafa;
  scroll-behavior: smooth; /* 平滑滚动效果 */

  .message {
    display: flex;
    gap: 12px;
    animation: fadeIn 0.3s ease-out;
  }

  .user-message {
    flex-direction: row-reverse;
  }

  .avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    font-size: 14px;
    color: white;
  }

  .user-avatar {
    background: linear-gradient(135deg, #1890ff 0%, #597ef7 100%);
  }

  .bot-avatar {
    background: linear-gradient(135deg, #13c2c2 0%, #52c41a 100%);
  }

  .message-content {
    max-width: 80%;
    padding: 12px 16px;
    border-radius: 10px;
    line-height: 1.5;
    font-size: 14px;
    position: relative;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    pre {
      background: rgba(245, 245, 245, 0.9);
      border-radius: 6px;
      padding: 10px;
      overflow-x: auto;
      margin: 10px 0;
      font-size: 13px;
      color: #333;
      border: 1px solid #e8e8e8;
    }

    code {
      font-family: 'Fira Code', monospace;
    }
  }

  .user-message .message-content {
    background: #1890ff;
    color: white;
    border-bottom-right-radius: 4px;
  }

  .bot-message .message-content {
    background: white;
    border: 1px solid #e8e8e8;
    color: #333;
    border-bottom-left-radius: 4px;
  }

  .timestamp {
    font-size: 11px;
    color: rgba(0, 0, 0, 0.4);
    margin-top: 4px;
    text-align: right;
  }

  .loading-dots {
    display: flex;
    gap: 6px;
    padding: 12px;
  }

  .dot {
    width: 6px;
    height: 6px;
    background: #52c41a;
    border-radius: 50%;
    animation: pulse 1.5s infinite ease-in-out;
  }

  .dot:nth-child(2) {
    animation-delay: 0.2s;
  }

  .dot:nth-child(3) {
    animation-delay: 0.4s;
  }
}

.input-area {
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 10px;
  align-items: center;
  position: sticky;
  bottom: 0;
  z-index: 10;

  /deep/ .ant-input {
    background: white;
    border: 1px solid #d9d9d9;
    color: #333;
    padding: 10px 14px;
    border-radius: 10px;
    font-size: 14px;
    height: auto;
    transition: all 0.3s ease;
    flex: 1;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);

    &:focus {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }

    &:hover {
      border-color: #40a9ff;
    }
  }

  .send-button {
    background: linear-gradient(135deg, #1890ff 0%, #597ef7 100%);
    border: none;
    width: 42px;
    height: 42px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: transform 0.2s ease;
    box-shadow: 0 4px 10px rgba(24, 144, 255, 0.3);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(24, 144, 255, 0.4);
    }

    &:active {
      transform: translateY(1px);
    }

    i {
      font-size: 16px;
      color: white;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 60%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  30% {
    transform: scale(1.5);
    opacity: 0.7;
  }
}

@media (max-width: 768px) {
  .chat-container {
    border-radius: 0;
    box-shadow: none;
    border: none;
    height: 100vh !important;
  }

  .chat-content {
    padding: 8px !important;
    gap: 12px !important;

    .message-content {
      max-width: 85% !important;
      padding: 10px 12px !important;
      font-size: 13px !important;
    }
  }

  .input-area {
    padding: 10px 12px !important;
  }

  .avatar {
    width: 28px !important;
    height: 28px !important;
    font-size: 12px !important;
  }
}
</style>
